package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    //获取会话
    @Autowired
    private HttpSession session;
    //获取业务层会话
    @Autowired
    private UserService userService;

    //发送验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {
        //接收手机user对象
        //生成4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码: " + code);
        //发送验证码
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972", user.getPhone(), code);
        //将验证码存到session中,方便后面使用
        session.setAttribute(user.getPhone(), code);
        //返回结果
        return R.success("发送验证码短信成功");
    }

    //登录
    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map) {
        //获取会话
        String phone = map.get("phone");
        String userCode = map.get("code");
        String sessionCode = (String) session.getAttribute(phone);
        //调用业务层方法
        User loginUser = userService.login(phone, userCode, sessionCode);
        if (loginUser != null) {
            //清楚session,再将用户id写入session
            session.removeAttribute(phone);
            session.setAttribute("user", loginUser.getId());
            //System.out.println("id:" + loginUser.getId());
            return R.success(loginUser);
        }
        return R.error("登录失败");
    }
}
